﻿#if SERVICE
using System;
using System.IO;
using System.Diagnostics;
using Microsoft.Win32;

namespace Net.Helper
{
    /// <summary>
    /// 应用程序帮助类
    /// </summary>
    public class ApplicationHelper
    {
        private static Process monitorProcess;

        /// <summary>
        /// 崩溃重启处理
        /// </summary>
        public static void CrashRecovery()
        {
            AppDomain.CurrentDomain.ProcessExit += ProcessExitHandler;
            var process = Process.GetCurrentProcess();
            var dllPath = AppDomain.CurrentDomain.BaseDirectory + "Resources/ApplicationMonitor.dll";
            monitorProcess = Process.Start(new ProcessStartInfo("dotnet")
            {
                Arguments = $"{dllPath} {process.Id} {process.MainModule.FileName}",
                UseShellExecute = false,
            });
            if (Environment.OSVersion.Platform == PlatformID.Win32NT)
            {
                using (var key = Registry.LocalMachine.CreateSubKey(@"SYSTEM\CurrentControlSet\Control\Windows"))
                {
                    if (key != null)
                    {
                        key.SetValue("ErrorMode", 2, RegistryValueKind.DWord);
                    }
                }
            }
        }

        private static void ProcessExitHandler(object sender, EventArgs e)
        {
            monitorProcess.Kill();
        }
    }
}
#endif